package com.qingxin.sys.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.entity.SysPermission;
import com.qingxin.sys.entity.SysUser;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.SysPermissionService;
import com.qingxin.sys.support.QxLogin;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.utils.StringUtils;

/**
 * 管理系统-登录，首页
 * @author Administrator
 *
 */
@Controller
public class AdminAction extends BaseAction {
	
	@Autowired
	private SysPermissionService sysPermissionService;
	
	@RequestMapping(value="/login.do", method=RequestMethod.GET)
	public String login(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		LoginUser loginUser = getLoginUser(request);
		if(loginUser != null){
			return "redirect:/admin/index.do";
		}
		return "redirect:/admin/login.do";
	}
	
	/**
	 * 登录页
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/admin/login.do", method=RequestMethod.GET)
	public String admin_login(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		LoginUser loginUser = getLoginUser(request);
		if(loginUser != null){
			return "redirect:/admin/index.do";
		}
		request.getSession().setAttribute("login_kind", "admin");
		return "adminui/login";
	}
	
	
	/**
	 * 登录处理
	 * @param model
	 * @param captcha
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/admin/login.json", method=RequestMethod.POST)
	@ResponseBody
	public Object admin_login(ModelMap model, String captcha, @RequestHeader(value="qxlogin", required=false)String qxlogin, HttpServletRequest request) {
		if(StringUtils.isEmpty(captcha) || StringUtils.isEmpty(qxlogin)){
			return new SysError("登录信息无效");
		}
		String loginname = null;
		String passwd = null;
		try {
			QxLogin qxLogin = new QxLogin(qxlogin);
			loginname = qxLogin.getLoginname();
			passwd = qxLogin.getPasswd();
		} catch (Exception e) {
			e.printStackTrace();
			return new SysError("登录信息无效");
		}
		
		if(StringUtils.isEmpty(loginname) || StringUtils.isEmpty(passwd) || !loginname.matches("^[0-9A-Za-z]{4,20}$")){
			return new SysError("登录信息无效");
		}
		
		String serverCaptcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if(StringUtils.isEmpty(serverCaptcha) || !serverCaptcha.equalsIgnoreCase(captcha)){
			return new SysError("captcha", "验证码错误");
		}
		
		SysUser sysUser = sysUserService.getByProperty("login_name", loginname);
		if(sysUser == null){
			return new SysError("登录信息错误.");
		}
		passwd = StringUtils.md5(passwd+sysUser.getSalt());
		if(!sysUser.getPassword().equalsIgnoreCase(passwd)){
			return new SysError("登录信息错误.");
		}
		
		LoginUser loginUser = new LoginUser();
		loginUser.setUserid(sysUser.getUserid());
		loginUser.setLogin_name(sysUser.getLogin_name());
		loginUser.setUser_type(sysUser.getUser_type());
		loginUser.setUser_status(sysUser.getUser_status());
		loginUser.setUser_kind(sysUser.getUser_kind());
		
		
		if(!SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
			String login_kind = (String) request.getSession().getAttribute("login_kind");
			if(login_kind == null){
				return new SysError("登录信息错误.");
			}
			boolean canLogin = false;
			switch (login_kind) {
			case "admin": 
				canLogin = "1".equals(sysUser.getUser_kind());//市县用户
				break;
			case "xz": 
				canLogin = "2".equals(sysUser.getUser_kind());//乡镇用户
				break;
			case "sc": 
				canLogin = ("3".equals(sysUser.getUser_kind()) || "6".equals(sysUser.getUser_kind()));//园区用户或企业用户
				break;
			case "nz": 
				canLogin = "4".equals(sysUser.getUser_kind());//农资用户
				break;
			case "jc": 
				canLogin = "5".equals(sysUser.getUser_kind());//质量检测
				break;
			}
			if(!canLogin){
				return new SysError("登录信息错误.");
			}
			
			if(!"1".equals(sysUser.getUser_status())){
				return new SysError("该账号已停用，不能登录. 请联系系统管理员解决该问题.");
			}
		}
		
		request.getSession().setAttribute(SystemCfg.SESSION_LOGIN_USERID, loginUser.getUserid());
		
		return "{\"code\":200}";
	}
	
	
	/**
	 * 注销处理
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/admin/logout.do", method=RequestMethod.GET)
	public String admin_logout(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(SystemCfg.SESSION_LOGIN_USERID);
		return "redirect:/admin/login.do";
	}
	
	
	
	/**
	 * 首页
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/admin/index.do", method=RequestMethod.GET)
	public String admin_index(ModelMap model, HttpServletRequest request){
		LoginUser loginUser = getLoginUser(request);
		model.put("loginUser", loginUser);
		request.getSession().setAttribute("login_kind", "admin");
		return "adminui/index";
	}
	
	
	
	
	/**
	 * 加载树形数据
	 * @param pid
	 * @return
	 */
	@RequestMapping(value="/admin/getMenudata.json", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object getMenudata(HttpServletRequest request){
		List<SysPermission> list = sysPermissionService.getMenudata();
		List<Map<String, String>> menulist = new ArrayList<>();
		LoginUser loginUser = getLoginUser(request);
		String path = request.getContextPath();
		if(list != null){
			if(SystemCfg.isSystemAdminUser(loginUser)){
				for(SysPermission permission : list){
					Map<String, String> map = new HashMap<>();
					map.put("id", permission.getPerid());
					map.put("pid", permission.getPid());
					map.put("url", StringUtils.isEmpty(permission.getUrl()) ? "#" : (path + permission.getUrl()));
					map.put("icon", permission.getIcon());
					map.put("name", permission.getPer_name());
					menulist.add(map);
				}
			}else if(SystemCfg.isAdminUser(loginUser)){
				for(SysPermission permission : list){
					if("system_ROLE".equalsIgnoreCase(permission.getPer_code())
							|| "perm".equalsIgnoreCase(permission.getPer_code())){
						continue;
					}
					
					Map<String, String> map = new HashMap<>();
					map.put("id", permission.getPerid());
					map.put("pid", permission.getPid());
					map.put("url", StringUtils.isEmpty(permission.getUrl()) ? "#" : (path + permission.getUrl()));
					map.put("icon", permission.getIcon());
					map.put("name", permission.getPer_name());
					menulist.add(map);
				}
			}else {
				Set<String> rights = sysPermissionService.getUserPermissionCodes(loginUser.getUserid());
				if(rights != null && rights.size() > 0){
					for(SysPermission permission : list){
						if("system_ROLE".equalsIgnoreCase(permission.getPer_code())
								|| "perm".equalsIgnoreCase(permission.getPer_code())){
							continue;
						}
						
						if(rights.contains(permission.getPer_code().toUpperCase()) || "map".equalsIgnoreCase(permission.getPer_code())){
							Map<String, String> map = new HashMap<>();
							map.put("id", permission.getPerid());
							map.put("pid", permission.getPid());
							map.put("url", StringUtils.isEmpty(permission.getUrl()) ? "#" : (path + permission.getUrl()));
							map.put("icon", permission.getIcon());
							map.put("name", permission.getPer_name());
							menulist.add(map);
						}
					}
				}
			}
		}
		return menulist;
	}
	
	
	/**
	 * 高平市追溯系统乡镇管理系统 登录页
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/xz/login.do", method=RequestMethod.GET)
	public String xz_login(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		LoginUser loginUser = getLoginUser(request);
		if(loginUser != null){
			return "redirect:/xz/index.do";
		}
		request.getSession().setAttribute("login_kind", "xz");
		return "adminui/xz_login";
	}
	
	
	/**
	 * 高平市追溯系统乡镇管理系统 注销处理
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/xz/logout.do", method=RequestMethod.GET)
	public String xz_logout(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(SystemCfg.SESSION_LOGIN_USERID);
		return "redirect:/xz/login.do";
	}
	
	
	/**
	 * 高平市追溯系统乡镇管理系统 首页
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/xz/index.do", method=RequestMethod.GET)
	public String xz_index(ModelMap model, HttpServletRequest request){
		LoginUser loginUser = getLoginUser(request);
		model.put("loginUser", loginUser);
		request.getSession().setAttribute("login_kind", "xz");
		return "adminui/xz_index";
	}
	
	
	/**
	 * 高平市农产品生产管理系统 登录页
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/sc/login.do", method=RequestMethod.GET)
	public String sc_login(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		LoginUser loginUser = getLoginUser(request);
		if(loginUser != null){
			return "redirect:/sc/index.do";
		}
		request.getSession().setAttribute("login_kind", "sc");
		return "adminui/sc_login";
	}
	
	
	/**
	 * 高平市农产品生产管理系统 注销处理
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/sc/logout.do", method=RequestMethod.GET)
	public String sc_logout(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(SystemCfg.SESSION_LOGIN_USERID);
		return "redirect:/sc/login.do";
	}
	
	
	/**
	 * 高平市农产品生产管理系统 首页
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/sc/index.do", method=RequestMethod.GET)
	public String sc_index(ModelMap model, HttpServletRequest request){
		LoginUser loginUser = getLoginUser(request);
		model.put("loginUser", loginUser);
		request.getSession().setAttribute("login_kind", "sc");
		return "adminui/sc_index";
	}
	
	
	/**
	 * 高平市农产品质量检测管理系统 登录页
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/jc/login.do", method=RequestMethod.GET)
	public String jc_login(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		LoginUser loginUser = getLoginUser(request);
		if(loginUser != null){
			return "redirect:/jc/index.do";
		}
		request.getSession().setAttribute("login_kind", "jc");
		return "adminui/jc_login";
	}
	
	
	/**
	 * 高平市农产品质量检测管理系统 注销处理
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/jc/logout.do", method=RequestMethod.GET)
	public String jc_logout(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(SystemCfg.SESSION_LOGIN_USERID);
		return "redirect:/jc/login.do";
	}
	
	
	/**
	 * 高平市农产品质量检测管理系统 首页
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/jc/index.do", method=RequestMethod.GET)
	public String jc_index(ModelMap model, HttpServletRequest request){
		LoginUser loginUser = getLoginUser(request);
		model.put("loginUser", loginUser);
		request.getSession().setAttribute("login_kind", "jc");
		return "adminui/jc_index";
	}
	
	
	/**
	 * 农资用户登录页
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/nz/login.do", method=RequestMethod.GET)
	public String nz_login(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		LoginUser loginUser = getLoginUser(request);
		if(loginUser != null){
			return "redirect:/nz/index.do";
		}
		request.getSession().setAttribute("login_kind", "nz");
		return "adminui/nz_login";
	}
	
	
	/**
	 * 农资用户注销处理
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/nz/logout.do", method=RequestMethod.GET)
	public String nz_logout(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(SystemCfg.SESSION_LOGIN_USERID);
		return "redirect:/nz/login.do";
	}
	
	
	/**
	 * 农资用户首页
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/nz/index.do", method=RequestMethod.GET)
	public String nz_index(ModelMap model, HttpServletRequest request){
		LoginUser loginUser = getLoginUser(request);
		model.put("loginUser", loginUser);
		request.getSession().setAttribute("login_kind", "nz");
		return "adminui/nz_index";
	}
	
	
	
}
